from tkinter import *
from sqlmood import myapi, sqlmood
from PIL import Image, ImageTk
import cv2
import time

img = None
num = 1
dicts = dicts = {}


def filepath(img):
    filePath = 'photo' + '/' + img
    return filePath


def take_snapshot():
    global img
    global num
    global dicts
    cv2.imwrite("photo/" + str(num) + ".jpg", img)
    print("拍照成功！")
    api = myapi()
    dicts = api.into(filepath(str(num) + ".jpg"))
    # dicts = api.into(filepath("P1.jpg"))
    # api.out(filepath('P1.jpg'))
    t1.delete(0.0, END)
    t2.delete(0.0, END)
    t1.insert(END, '车牌号：'+dicts['number'])
    t2.insert(END, dicts['end'])
    num += 1
def video_loop():
    num = 1
    global img
    success, img = camera.read()  # 从摄像头读取照片
    if success:
        cv2.waitKey(1000)
        cv2image = cv2.cvtColor(img, cv2.COLOR_BGR2RGBA)  # 转换颜色从BGR到RGBA
        current_image = Image.fromarray(cv2image)  # 将图像转换成Image对象
        imgtk = ImageTk.PhotoImage(image=current_image)
        panel.imgtk = imgtk
        panel.config(image=imgtk)
        root.after(1, video_loop)


def main(event):
    if event.char == 's':
        take_snapshot()


camera = cv2.VideoCapture(0)  # 摄像头

root = Tk()
root.title("opencv + tkinter")
root.bind("<Key>", main)

panel = Label(root)  # initialize image panel
panel.pack(padx=10, pady=10)
root.config(cursor="arrow")
t1 = Text(root,height=1,width=30,font = ('微软雅黑',12))
t1.pack(pady = 10)
t2 = Text(root,height=1,width=30,font = ('微软雅黑',12))
t2.pack(pady = 10)
video_loop()

root.mainloop()
# 当一切都完成后，关闭摄像头并释放所占资源
camera.release()
cv2.destroyAllWindows()
